package com.cictec.middleware.tde.rm.protocol.rm.encode;

import java.nio.ByteBuffer;

import com.cictec.middleware.commons.utils.BinaryUtils;
import com.cictec.middleware.tde.exception.MessageEncoderException;
import com.cictec.middleware.tde.rm.protocol.AbstractMessageEncoder;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.annotion.TerminalMessageEncoder;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x24TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.utils.RmBinaryUtils;

/**
 * 0x24 刷卡上报
 * 
 * @author Administrator
 *
 */
@TerminalMessageEncoder(0x24)
public class Rm0x24Encoder extends AbstractMessageEncoder {

	@Override
	public byte[] encode(TerminalMessage message) throws MessageEncoderException {
		
		Rm0x24TerminalMessage msg = (Rm0x24TerminalMessage) message;

		ByteBuffer out = ByteBuffer.allocate(256);

		out.put(RmBinaryUtils.dateToDwordRM(msg.getCreateTime()));
		out.put(BinaryUtils.intToUnsignedByte(msg.getReaderMainVersion()));
		out.put(BinaryUtils.intToUnsignedByte(msg.getReaderSubVersion()));

		String card = msg.getCardNumber();
		byte[] b = toByteArray(Long.parseLong(card), 4); // 整型到字节，
		out.put(b);
		
		/** 预留 HEX 2 字节 见刷卡标识表 
		 * 刷卡标识表：<br>
		 * 		Bit7 	Bit6 	Bit5 	Bit4 	Bit3	Bit2	Bit1	Bit0<br>
		 *	0 													签到 	司机卡<br>
		 *	1 	预留 	预留 	预留 	预留 	预留 	预留 	签退 	维护卡<br>
		 *		Bit15 	Bit14 	Bit13 	Bit12 	Bit11 	Bit10 	Bit9 	Bit8<br>
		 *	0<br>
		 *	1 	预留 	预留	 	预留 	预留 	预留		 预留 	预留		预留<br>*/
		
		out.put(BinaryUtils.intToDword(msg.getReserved()));
		return toBytes(out);
	}
	
	public static void main(String args[]) {
		Long i = 1L;
		byte[] b = toByteArray(i, 4); // 整型到字节，

		System.out.println("212123 bin: " + Integer.toBinaryString(212123));// 212123的二进制表示
		System.out.println("212123 hex: " + Integer.toHexString(212123)); // 212123的十六进制表示

		for (int j = 0; j < 4; j++) {
			System.out.println("b[" + j + "]=" + b[j]);// 从低位到高位输出,java的byte范围是-128到127
		}

		int k = toInt(b);// 字节到整型，转换回来
		System.out.println("byte to int:" + k);

	}

	// 将iSource转为长度为iArrayLen的byte数组，字节数组的低位是整型的低字节位
	public static byte[] toByteArray(Long iSource, int iArrayLen) {
		byte[] bLocalArr = new byte[iArrayLen];
		for (int i = 0; (i < 4) && (i < iArrayLen); i++) {
			bLocalArr[i] = (byte) (iSource >> 8 * i & 0xFF);

		}
		return bLocalArr;
	}

	// 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位
	public static int toInt(byte[] bRefArr) {
		int iOutcome = 0;
		byte bLoop;

		for (int i = 0; i < 4; i++) {
			bLoop = bRefArr[i];
			iOutcome += (bLoop & 0xFF) << (8 * i);

		}

		return iOutcome;
	}
	

}
